<?php
namespace Admin\Logic;

use Admin\Common\Category;
use Think\Log;

class FoodLogic
{

    /**
     * 获取库存数据
     * @param int $id
     * @return bool|mixed
     */
    public static function getAll()
    {
        try {
            $stock = D('Food as f');
            $data = $stock
                ->join('left join food_cate_food as c on f.cate_id = c.id')     //连接 分类 表
                ->field('f.*,c.cate_name')
                ->select();
            return $data;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 根据id 获取修改库存所需的数据
     * @param $id
     * @return bool|mixed
     */
    public static function getStockById($id)
    {
        // 根据id获取数据
        try{
            $stock = D('Food as f');
            $data = $stock
                ->where(['id'=>$id])
                ->find();
            return $data;
        }catch (\Exception $e){
            return false;
        }

    }

    public static function addStockLogByFood($food_id)
    {
        // 根据菜谱id找到对应的库存和损耗
        $stock = M('food_detail_log as d')
            ->join('food_stock as s on d.stock_id=s.id')
            ->field('d.*,s.goods_name,s.goods_price')
            ->where(['food_id'=>$food_id])
            ->select();

    }

    public static function getFoodDetail($id)
    {

        // 根据id获取数据
        try{
            $res = M('food_detail_log as f')
                ->join('food_stock as s on s.id=f.stock_id')
                ->field('f.*,s.cat_id')
                ->where(['f.food_id'=>$id])
                ->select();
            return $res;
        }catch (\Exception $e){
            return false;
        }

    }

    /**
     * 根据菜谱id查询出菜谱价格
     * @param $food_id
     * @return bool|mixed
     */
    public static function getFoodPrice($food_id)
    {

        // 根据id获取数据
        try{
            $res = M('Food')
                ->where(['id'=>$food_id])
                ->field(['price'])
                ->find();
            return $res['price']/100;
        }catch (\Exception $e){
            return false;
        }

    }

    /**
     * 根据 商品名称 获取修改库存所需的数据
     * @param $name
     * @return bool|mixed
     */
    public static function getStockByName($name)
    {
        // 根据id获取数据
        try{
            $stock = D('Food as f');
            $data = $stock
                ->join('food_cate_food as c on f.cate_id = c.id')     //连接 分类 表
                ->where(['f.name'=>['like','%'.$name.'%']])
                ->field('f.*,c.cate_name')
                ->select();
            return $data;
        }catch (\Exception $e){
            return false;
        }

    }


    /**
     * 插入库存改动记录
     * @param $old_stock    $旧的库存
     * @param $new_stock    $新的库存
     * @param $arr      $更改的数据
     * @return bool|mixed
     */
    public static function isStockRecord($old_stock, $new_stock, $arr)
    {
        // 改动的值
        $stock_type = $old_stock>$new_stock?0:1;
        $stock = $stock_type==0?$old_stock-$new_stock:$new_stock-$old_stock;
        try{
            $stock_detail = D('StockDetail');
            $data = [
                'stock_id' => $arr['id'],
                'goods_name' => $arr['goods_name'],
                'unit' => $arr['unit'],
                'goods_price' => $arr['goods_price'],
                'stock' => $stock,
                'stock_type' => $stock_type,
                'remark' => $arr['remark'],
                'user_name' => $arr['user_name'],
                'created_at' => getDateTime(),
            ];
            $result = $stock_detail->add($data);
            return  $result;
        }catch (\Exception $e){
            return false;
        }


    }

    /**
     * 执行修改库存操作
     * @param $data
     * @return bool
     */
    public static function update($data)
    {
        try {
            $res = [
                'id' => $data['id'],
                'name' => $data['name'],
                'cate_id' => $data['cate_id'],
                'unit' => $data['unit'],
                'price' => $data['price']*100,
                'taste' => $data['taste'],
                'is_show' => $data['is_show']=='on'?'上架':'下架',
                'loss' => $data['loss'],
                'create_at' => getDateTime(),
            ];

            $id = D('Food')->save($res);

            if($id !== false){
                // 先删除所有菜谱明细
                M('food_detail_log')->where(['food_id'=>$data['id']])->delete();
                // 添加明细
                $arr = [];
                foreach ($data['food'] as $k=>$v){
                    $arr[$k]['food_id'] = $data['id'];
                    $arr[$k]['stock_id'] = $v['stock_id'];
                    $arr[$k]['deal_name'] = $v['name'];
                    $arr[$k]['deal_value'] = $v['deal_value'];
                    $arr[$k]['created_at'] = getDateTime();
                }
                $result = M('food_detail_log')->addAll($arr);
                if($result){
                    return $result;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }

    }

    /**
     * 执行添加库存操作
     * @param $data
     * @return bool
     */
    public static function create($data)
    {
        try {
            $model = M();
            $model->startTrans(); //开启事务
            $flag = true;
            $res = [
                'name' => $data['name'],
                'cate_id' => $data['food_cate_id'],
                'unit' => $data['unit'],
                'price' => $data['price']*100,
                'taste' => $data['taste'],
                'is_show' => $data['is_show']=='on'?'上架':'下架',
                'loss' => $data['loss'],
                'create_at' => getDateTime(),
            ];
            $id = D("Food")->add($res);
            if ($id === false) {
                $flag = false;
            }
            $arr = [];
            //拼装菜谱明细表数据
            foreach ($data['food'] as $k => $v) {
                $arr[$k]['food_id'] = $id;
                $arr[$k]['stock_id'] = $v['stock_id'];
                $arr[$k]['deal_name'] = $v['name'];
                $arr[$k]['deal_value'] = $v['deal_value'];
                $arr[$k]['created_at'] = getDateTime();
            }
            
            $result = M('food_detail_log')->addAll($arr);
            
            if ($result === false) {
                $flag = false;
            }

            if ($flag) { //提交事务
                $model->commit();
                return true;
            } else {
                $model->rollback();
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 删除单条数据
     * @param $id
     * @return mixed
     */
    public static function delete($id)
    {
        try {
            $data = D('Food')->where(['id'=>$id])->delete();
            // 删除其 菜谱材料

            return $data;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 提交订单获取菜品总金额
     * @param  string $ids [description]
     * @return [type]      [description]
     */
    public static function getOrderTotal($ids = '')
    {
        try {
            $food = D('Food')->where(['id' => ['in', implode(',', $ids)]])->select();
            $total = array_sum(array_map(function ($val) {
                return $val['price'];
            }, $food));

            return $total;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * [获取指定条件的菜谱材料组成]
     * @param  array  $where [description]
     * @return [type]     [description]
     */
    public static function getFindAll($where)
    {
        try {
            $food = M('food_detail_log')->where(['food_id' => ['in', implode(',', $where)]])->select();
            $data = [];
            
            foreach ($food as $key => $value) {
                $data[$value['food_id']][] = $value;
            }
            
            return $food;
        } catch (\Exception $e) {
            return false;
        }
    }

    public static function  getOrderFoodStock($food_id = [])
    {
        try{
            $res = D('food_detail_log as f')
                ->where(['f.food_id'=>['in',$food_id]])
                ->join('left join food_stock as s on f.stock_id=s.id')
                ->field(['s.goods_name,f.deal_value,f.food_id'])
                ->select();
            $data = [];
            foreach ($res as $k=>$v)
            {
                $data[] = [$v['goods_name'],$v['deal_value'],$v['food_id']];
            }
            return $data;

        } catch (\Exception $e){
            return false;
        }
    }


    /**
     * 根据菜谱i计算出相应的库存损耗
     * @param $food_id
     * @return float|int
     *
     */
    public static function getStockLoss($food_id,$num = 1)
    {
        $stock = M('food_detail_log as f')
            ->where(['food_id'=>$food_id])
            ->join('left join food_stock as s on f.stock_id=s.id')
            ->field(['f.stock_id,f.deal_value,s.goods_price'])
            ->select();
        $loss = 0;
        foreach ($stock as $k=>$v)
        {
            // 库存损耗 = （价格/100 * 数量）* 菜谱数量
            $loss += (($v['goods_price']/100) * ($v['deal_value'])) * $num;
        }
        return $loss;
    }


}